package com.example.administrator.xin;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.xin.bean.JsonBean;
import com.example.administrator.xin.wheelview.WheelView;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    private Context context;
    private static final String[] PLANETS = new String[]{"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Uranus", "Neptune", "Pluto"};
    private static final String[] NUMBERCHARGE = new String[]{"免费", "5", "10", "15", "30", "50", "100"};
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = MainActivity.this;
        setContentView(R.layout.activity_main);
        WheelView wva = (WheelView) findViewById(R.id.wheel_view);

        wva.setItems(Arrays.asList(PLANETS), 1);//init selected position is 1 初始选中位置为1
        wva.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int selectedIndex, String item) {
                Log.d("cdy", "selectedIndex: " + selectedIndex + ", item: " + item);
            }

        });
    }

    public void onClick1(View view) {
        new AlertDialog(context).builder()
                .setMsg("你现在无法接收到新消息提醒。请到系统-设置-通知中开启消息提醒")
                .setPositiveButton("确认退出", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void onClick2(View view) {

    }

    public void onClick(View view) {
        new AlertDialog(context).builder().setTitle("退出当前账号")
                .setMsg("是否删除所有信息？")
                .setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void onClick3(View view) {
        new AlertDialog(context).builder()
                .setMsg("是否删除信息？")
                .setPositiveButton("删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void onClick4(View view) {
        new AlertDialog(context).builder()
                .setMsg("是否删除所有信息？")
                .setPositiveButton("删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void onClick5(View view) {
        new AlertDialog(context).builder()
                .setMsg("是否将所有信息标记为已读？")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void onClick6(View view) {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        View outerView = LayoutInflater.from(this).inflate(R.layout.dialog_charge, null);
        final WheelView wv = (WheelView) outerView.findViewById(R.id.options1);
        wv.setItems(Arrays.asList(NUMBERCHARGE), 0);//init selected position is 0 初始选中位置为0
        wv.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int selectedIndex, String item) {
                Log.d("cdy", "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item);
            }
        });
        TextView charge_option = (TextView) outerView.findViewById(R.id.tvHit);
        charge_option.setText("拍摄收费");
        TextView tv_ok = (TextView) outerView.findViewById(R.id.btnSubmit);
        TextView tv_cancel = (TextView) outerView.findViewById(R.id.btnCancel);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(MainActivity.this, "selectDateTime: " + wv.getSelectedItem(), Toast.LENGTH_SHORT).show();
            }
        });
        final Dialog dialog = new android.app.AlertDialog.Builder(this)
                .setView(outerView)
                .show();
        //点击取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    public void onClick7(View view) {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        View outerView = LayoutInflater.from(this).inflate(R.layout.dialog_charge, null);
        final WheelView wv = (WheelView) outerView.findViewById(R.id.options1);
        wv.setItems(Arrays.asList(NUMBERCHARGE), 0);//init selected position is 0 初始选中位置为0
        wv.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int selectedIndex, String item) {
                Log.d("cdy", "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item);
            }
        });
        TextView charge_option = (TextView) outerView.findViewById(R.id.tvHit);
        charge_option.setText("照片收费");
        TextView tv_ok = (TextView) outerView.findViewById(R.id.btnSubmit);
        TextView tv_cancel = (TextView) outerView.findViewById(R.id.btnCancel);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(MainActivity.this, "selectDateTime: " + wv.getSelectedItem(), Toast.LENGTH_SHORT).show();
            }
        });
        final Dialog dialog = new android.app.AlertDialog.Builder(this)
                .setView(outerView)
                .show();
        //点击取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    public void onClick8(View view) {
        new AlertDialog(context).builder()
                .setMsg("加入黑名单后，TA将无法对你进行关注，通话，私信，赞，打赏等功能")
                .setPositiveButton("加入黑名单", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void onClick9(View view) {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        View outerView = LayoutInflater.from(this).inflate(R.layout.dialog_charge, null);
        final WheelView wv = (WheelView) outerView.findViewById(R.id.options1);
        wv.setItems(Arrays.asList(NUMBERCHARGE), 0);//init selected position is 0 初始选中位置为0
        wv.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int selectedIndex, String item) {
                Log.d("cdy", "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item);
            }
        });
        TextView charge_option = (TextView) outerView.findViewById(R.id.tvHit);
        charge_option.setText("向TA收费");
        TextView tv_ok = (TextView) outerView.findViewById(R.id.btnSubmit);
        TextView tv_cancel = (TextView) outerView.findViewById(R.id.btnCancel);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(MainActivity.this, "selectDateTime: " + wv.getSelectedItem(), Toast.LENGTH_SHORT).show();
            }
        });
        final Dialog dialog = new android.app.AlertDialog.Builder(this)
                .setView(outerView)
                .show();
        //点击取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    public void onClick10(View view) {
        View outerView = LayoutInflater.from(this).inflate(R.layout.dialog_age, null);
        final WheelView wv = (WheelView) outerView.findViewById(R.id.age_options);
        wv.setItems(getNumbers(), 17);//init selected position is 0 初始选中位置为0
        wv.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int selectedIndex, String item) {
                Log.d("cdy", "[Dialog]selectedIndex: " + selectedIndex + ", item: " + item);
            }
        });
        TextView tv_ok = (TextView) outerView.findViewById(R.id.btnSubmit);
        TextView tv_cancel = (TextView) outerView.findViewById(R.id.btnCancel);
        //点击确定
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(MainActivity.this, "selectDateTime: " + wv.getSelectedItem(), Toast.LENGTH_SHORT).show();
            }
        });
        final Dialog dialog = new android.app.AlertDialog.Builder(this)
                .setView(outerView)
                .show();
        //点击取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });

    }
    private static int AGE = 100;
    private ArrayList getNumbers() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 1; i < AGE; i++) {
            list.add(i + "");
        }
        return list;
    }


    final static String[] YEAR=new String[]{"2015年","2016年","2017年","2018年","2019年"};
    final static String[] MONTH=new String[]{"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"};
    public void onClick11(View view) {
        View outerView = LayoutInflater.from(this).inflate(R.layout.dialog_select_time, null);
        //年份滚轮
        final WheelView wv1 = (WheelView) outerView.findViewById(R.id.time_options1);
        //月份滚轮
        final WheelView wv2 = (WheelView) outerView.findViewById(R.id.time_options2);
        wv1.setItems(Arrays.asList(YEAR), 2);
        wv2.setItems(Arrays.asList(MONTH), 0);
        TextView tv_ok = (TextView) outerView.findViewById(R.id.btnSubmit);
        TextView tv_cancel = (TextView) outerView.findViewById(R.id.btnCancel);
        //点击确定
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String mSelectCity1 = wv1.getSelectedItem();
                String mSelectCity2 = wv2.getSelectedItem();
                Toast.makeText(MainActivity.this, "selectDateTime: " + mSelectCity1 + mSelectCity2, Toast.LENGTH_SHORT).show();
            }
        });
        //点击取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            }
        });
        new android.app.AlertDialog.Builder(this)
                .setView(outerView)
                .show();
    }



    public void onClick13(View view) {
        new AlertDialog(context).builder()
                .setMsg("有信息未保存，是否退出？")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }


    public void onClick12(View view) {
        //一定要先加载 mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        View outerView = LayoutInflater.from(this).inflate(R.layout.dialog_select_location, null);
        //省级滚轮
        final WheelView wv1 = (WheelView) outerView.findViewById(R.id.location_options1);
        //市级滚轮
        final WheelView wv2 = (WheelView) outerView.findViewById(R.id.location_options2);
        //县级滚轮
        final WheelView wv3 = (WheelView) outerView.findViewById(R.id.location_options3);

        String[] A = new String[options1Items.size()];
        String[] B = new String[options2Items.get(0).size()];
        String[] C = new String[options3Items.get(0).get(0).size()];
        Log.d("cdy", "onClick8: " + A.length);
        for (int i = 0; i < A.length; i++) {
            A[i] = options1Items.get(i).getPickerViewText();
            //Log.d("cdy", "onClick8: "+options1Items.get(i).getPickerViewText());
        }
        for (int i = 0; i < B.length; i++) {
            B[i] = options2Items.get(0).get(i);
            //Log.d("cdy", "onClick8: "+options1Items.get(i).getPickerViewText());
        }
        for (int i = 0; i < C.length; i++) {
            C[i] = options3Items.get(0).get(0).get(i);
            //Log.d("cdy", "onClick8: "+options1Items.get(i).getPickerViewText());
        }
        wv1.setItems(Arrays.asList(A), 0);
        wv2.setItems(Arrays.asList(B), 0);
        wv3.setItems(Arrays.asList(C), 0);

        //联动逻辑效果
        wv1.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index, String item) {
                String[] B = new String[options2Items.get(index).size()];
                for (int i = 0; i < B.length; i++) {
                    B[i] = options2Items.get(index).get(i);
                }
                wv2.setItems(Arrays.asList(B), 0);
                String[] C = new String[options3Items.get(index).get(0).size()];
                for (int i = 0; i < C.length; i++) {
                    C[i] = options3Items.get(index).get(0).get(i);
                }
                wv3.setItems(Arrays.asList(C), 0);
            }
        });
        wv2.setOnItemSelectedListener(new WheelView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index, String item) {
                int postion = wv1.getSelectedPosition();
                String[] C = new String[options3Items.get(postion).get(index).size()];
                for (int i = 0; i < C.length; i++) {
                    C[i] = options3Items.get(postion).get(index).get(i);
                }
                wv3.setItems(Arrays.asList(C), 0);
            }
        });

        TextView tv_ok = (TextView) outerView.findViewById(R.id.btnSubmit);
        TextView tv_cancel = (TextView) outerView.findViewById(R.id.btnCancel);
        //点击确定
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String mSelectCity1 = wv1.getSelectedItem();
                String mSelectCity2 = wv2.getSelectedItem();
                String mSelectCity3 = wv3.getSelectedItem();
                Toast.makeText(MainActivity.this, "selectDateTime: " + mSelectCity1 + mSelectCity2 + mSelectCity3, Toast.LENGTH_SHORT).show();
            }
        });
        //点击取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            }
        });
        new android.app.AlertDialog.Builder(this)
                .setView(outerView)
                .show();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        Toast.makeText(context, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(context, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(context, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
